﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using Amazon.Route53.DataContracts;
using System.Xml.Serialization;
using System.Xml;

namespace Amazon.Route53
{
    public static class Extensions
    {
        public static Exception 
            PrepareException(this System.ServiceModel.ProtocolException PE)
        {
            var we = PE.InnerException as System.Net.WebException;

            if (we != null)
            {
                var response = we.Response;
                try
                {
                    var bytes = new byte[response.ContentLength];
                    System.IO.Stream stream = response.GetResponseStream();
                    stream.Read(bytes, 0, bytes.Length);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    String xml = System.Text.Encoding.UTF8.GetString(bytes);
                    //System.Xml.XmlTextReader Reader = new XmlTextReader(xml, XmlNodeType.Document, null);
                    var doc = new XmlDocument();
                    doc.LoadXml(xml);
                    if (doc.LastChild.Name.Equals("ErrorResponse", StringComparison.InvariantCultureIgnoreCase))
                    {
                        DataContractSerializer DS = new DataContractSerializer(typeof(ErrorResponse));
                        var error = DS.ReadObject(stream) as ErrorResponse;
                        return new Route53Exception(we, error);
                    }
                    else if (doc.LastChild.Name.Equals("InvalidChangeBatch", StringComparison.InvariantCultureIgnoreCase))
                    {
                        DataContractSerializer DS = new DataContractSerializer(typeof(InvalidChangeBatch));
                        var batchList = DS.ReadObject(stream) as InvalidChangeBatch;
                        return new InvalidChangeBatchException(we, batchList.Messages.ToArray());
                    }
                    else if (doc.LastChild.Name.Equals("AccessDeniedException", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return new AccessDeniedException(doc.LastChild.FirstChild.InnerText, we);
                    }

                }
                catch { }
  
            }
            return PE;
        }
    }
}
